package com.practice.bootdemo.config;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author :admin
 * @description: TODO edit class Description
 * @create date: 2019/12/12 22:22
 */
@Slf4j
@Aspect
@Configuration
public class GlobalLogConfig {


    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void logPointCut() {

    };

    @Before("logPointCut()")
    public void printLog(final JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("=========》requestUrl：{}",request.getRequestURL());
        log.info("====> methodName= {} param = {}",joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        long startTime=System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        Gson gson=new Gson();
        log.info("====> response:{},耗时:{}ms", gson.toJson(result), System.currentTimeMillis() - startTime);
        return result;
    }
}
